package org.example.infrastructure.persistent.repository;

import org.example.domain.user_participate.model.entity.LotteryRecordEntity;
import org.example.domain.user_participate.repository.IUserParticipateRepo;
import org.example.infrastructure.persistent.dao.ILotteryRecordDao;
import org.example.infrastructure.persistent.dao.IUserActivityDao;
import org.example.infrastructure.persistent.po.LotteryRecordPO;
import org.example.infrastructure.redis.IRedisService;
import org.example.types.common.RedisKeysPrefix;
import org.redisson.api.RKeys;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lxc18
 * @date 2025/3/14 21:00
 * @description UserParticipateRepo
 */
@Repository
public class UserParticipateRepo implements IUserParticipateRepo {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private IUserActivityDao userActivityDao;
    @Resource
    private ILotteryRecordDao lotteryRecordDao;
    @Override
    public int queryUserParticipateQuota(Long userId,Long activityId) {
        String key = RedisKeysPrefix.USER_PARTICIPATE_QUOTA+userId;

        RMap<Long, Integer> map = redissonClient.getMap(key);
        Integer quota = map.get(activityId);
        if(quota != null){
            quota = (int) quota;
        }
        else{
            //调用mapper方法
            quota = userActivityDao.queryUserParticipateQuota(userId,activityId);
            map.put(activityId, quota);
        }
        //        查看redis所有key

        return quota;
    }

    @Override
    public int queryUserUsedQuota(Long userId, Long activityId) {
        String key = RedisKeysPrefix.USER_PARTICIPATE_USED_QUOTA+userId;
        RMap<Long, Integer> map = redissonClient.getMap(key);
        Integer quota = map.get(activityId);
        if(quota != null){
            quota = (int) quota;
        }
        else{
            //调用mapper方法
            quota = userActivityDao.queryUserUsedQuota(userId,activityId);
            map.put(activityId, quota);
        }
        //        查看redis所有key
        return quota;
    }

    @Override
    public boolean addUserParticipateQuota(Long userId,Long activityId, int quotaNum) {
        String key = RedisKeysPrefix.USER_PARTICIPATE_QUOTA + userId;
        //先要查询
        int quota = queryUserParticipateQuota(userId,activityId);
        try {
            RMap<Long, Integer> map = redissonClient.getMap(key);
            map.put(activityId, quota+quotaNum);

            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public List<LotteryRecordEntity> queryUserLotteryRecord(Long id) {
        List<LotteryRecordPO> recordPOList = lotteryRecordDao.queryUserLotteryRecordByUserId(id);
        List<LotteryRecordEntity> lotteryRecordEntities = new ArrayList<LotteryRecordEntity>();
        for(LotteryRecordPO recordPO : recordPOList){
            LotteryRecordEntity recordEntity = LotteryRecordEntity.builder()
                        .recordId(recordPO.getRecordId())
                        .userId(recordPO.getUserId())
                        .activityId(recordPO.getActivityId())
                        .status(recordPO.getStatus())
                        .createTime(recordPO.getCreateTime())
                        .updateTime(recordPO.getUpdateTime())
                        .build();
            lotteryRecordEntities.add(recordEntity);
        }
        return lotteryRecordEntities;
    }

    //更新缓存到数据库中
    @Override
    public void updateCacheToDB() {
        String cacheKey = RedisKeysPrefix.USER_PARTICIPATE_QUOTA;
        //获取所有前缀为key的key
        // 获取所有用户的键
        RKeys keys = redissonClient.getKeys();
        Iterable<String> userKeys = keys.getKeysByPattern(cacheKey + "*");
        // 遍历每个用户的 Hash，获取活动额度
        for (String key : userKeys) {
            RMap<Long, Integer> userQuotaMap = redissonClient.getMap(key);
            System.out.println("User " + key + " quotas:");
            Long userId = Long.parseLong(key.substring(cacheKey.length()));
            for (Map.Entry<Long, Integer> entry : userQuotaMap.entrySet()) {
                // userId,activityId,quota
                Long activityId = entry.getKey();
                int quota = entry.getValue();
                System.out.println("Activity " + activityId + ": " + quota);
                // 调用 Mapper 方法更新数据库
                userActivityDao.updateUserParticipateQuota(userId,activityId,quota);
            }
        }
        //更新用户活动已经抽奖额度
        String cacheKey2 = RedisKeysPrefix.USER_PARTICIPATE_USED_QUOTA;
        //获取所有前缀为key的key
        // 获取所有用户的键
        RKeys keys2 = redissonClient.getKeys();
        Iterable<String> userKeys2 = keys2.getKeysByPattern(cacheKey2 + "*");
        // 遍历每个用户的 Hash，获取活动额度
        for (String key : userKeys2) {
            RMap<Long, Integer> userQuotaMap = redissonClient.getMap(key);
            System.out.println("User " + key + " used_quotas:");
            Long userId = Long.parseLong(key.substring(cacheKey2.length()));
            for (Map.Entry<Long, Integer> entry : userQuotaMap.entrySet()) {
                // userId,activityId,quota
                Long activityId = entry.getKey();
                int quota = entry.getValue();
                System.out.println("Activity " + activityId + ": " + quota);
                // 调用 Mapper 方法更新数据库
                userActivityDao.updateUserUsedQuota(userId,activityId,quota);
            }
        }
    }
}
